<?php

namespace app\np\controller;

use app\base\controller\Base;
use think\Request;
use think\Cache;
use think\Config;
use think\Session;

class Usersoptionalstock extends Base
{
    public $model;

    public function __construct()
    {
        $this->model = model("UsersOptionalStock");
        $this->usermodel = model("Users");
        $this->sharesmodel = model("Shares");
        parent::__construct();
        $rows = Cache::get($this->Cstatic->get("sid"));
        $this->sid_user_id = $rows['id'];
    }

    /**
     * 添加自选股
     * @return \think\Response
     */
    public function addstock()
    {
        $user_id = $this->sid_user_id;
        $stock_id = $this->stockid;
        $res = $this->model->where(['user_id' => $user_id, 'stock_id' => $stock_id])->find();
        if ($res) {
            return resJson(0, $this->ecLang("havestock"));
        }
        $data = [
            "user_id" => $user_id,
            "stock_id" => $stock_id,
        ];
        $insert_id = $this->model->save($data);
        if ($insert_id) {
            return resJson(1, $this->ecLang("scuessInsert"),['id'=>$this->model]);
        } else {
            return resJson(0, $this->ecLang("failInsert"));
        }
    }

    /**
     * 删除自选股
     * @return \think\Response
     */
    public function delete()
    {
        $id = $this->id;
        $res = $this->model->delete(['id' => $id],true);

        if (empty($res)) {
            return failJson($this->ecLang("faildelete"));
        }
        return sucessJson($this->ecLang("scuessdelete"));
    }


        //自选列表展示
    public function lists()
    {
        $user_id = $this->sid_user_id;

        $shareModel = model("shares");
        $rowsAaray = [];
        $rowsAaray['res'] = [];
        $rowsAaray['pageInfo'] = [];
        $res = $this->model->stock_page(['a.user_id' => $user_id]);
        if(!empty($res)){
            $pageInfo = $res['pageInfo'];
            $res = $res['res'];

            foreach ($res as $k => $v) {
                $result = $shareModel->alias("a")
                    ->field("a.id,configs.key,a.code,configs.value")
                    ->where(['a.id' => $v['stock_id']])
                    ->join("configs", "a.attribute = configs.id", "left")
                    ->find();
                if (!empty($result)) {
                    $rows = gethqone($result['code'], $result['key']);
                    if (!empty($rows)) {
                        $rows['code'] = $result['code'];
                        $rows['value'] = $result['value'];
                        $rows['stock_id'] = $v['stock_id'];
                    }
                    $rowsAaray['res'][] = $rows;
                }




            }
            $rowsAaray['pageInfo'] =$pageInfo;
        }

        return resJson(1, $this->ecLang("query"), $rowsAaray['res'], $rowsAaray['pageInfo']);

    }

}
